
import http from './http.js'
import consts from './consts.js'
import global from "./global.js";
import { Message } from 'element-ui';
import ErrorCode from '../error/ErrorCode.js'

// function getCode(res){ 
//     return res.data && res.data.header && res.data.header.code
// }
function getCode(res){ 
    return res.data.code
}

export default (data, success, error, method, url, config) => {
    let option = {
        method: method,
        url: url,
    }
    if (data) {
        option.params = data.query
        option.data = data.body
    }
    if (!option.params) {
        option.params = {}
    }
    // option.params.t = new Date().getTime()
    if (config) {
        if (config.responseType) option.responseType = config.responseType;
    }
    return new Promise((resolve, reject) => {
        http(option).then((res) => {
            if (res.headers["content-type"] && res.headers["content-type"].indexOf("application/json") < 0) {
                success && success(res);
                resolve(res.data)
            }
            let businessCode=getCode(res)
            if ( businessCode== consts.CODE.SUCCESS) {
                success && success(res.data);
                resolve(res.data)
            } else if (businessCode == consts.CODE.AUTH_ERROR) {
                handleAuthError(res);
                handleError(error, res)
                reject(res.data)
            } else {
                handleError(error, res)
                reject(res)
            }
        }).catch((err) => {
            handleError(error, err)
            reject(err)
        });
    })
}

function handleError(errorFunc, res) {
    if (res && res.data) {
        let message = res.data.msg;
        let businessCode=getCode(res)
        if (ErrorCode[businessCode]) {
            message = ErrorCode[businessCode]
        }
        Message({
            message: message,
            type: 'error'
        });
    }
    if (errorFunc) {
        errorFunc(res);
    } else {
        console.log(res);
    }
}


function handleAuthError(res) {
    if (global.api && global.api.authCallback) {
        global.api.authCallback(res.data)
    } else {
        console.log(`WARNING: no auth error callback function! pls rewrite /http/global.api.authCallback `);
    }
}



